import {toComboBoxData, toObject} from "@/common/utils/page.util";

export const mixinForm = {
    props: {
        model: {},
        isCreate: true,
    },
    data() {
        return {
            rules: {},
            errors: {},
            messages: {}
        };
    },
    methods: {
        getError(name) {
            return this.errors[name] && this.errors[name].length
                ? this.errors[name][0]
                : null;
        },
        hasError(name) {
            return this.getError(name) != null;
        },
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid && Object.keys(valid).length > 0) {
                    let keys = Object.keys(valid);
                    let error = this.getError(keys[0]);
                    this.$toast.center(error)
                    return
                }
                if (this.isCreate) {
                    this.add({object: toObject(this.model)})
                } else {
                    this.update({object: toObject(this.model), conditions: this.updateCondition()})
                }
            })
        },
        updateCondition() {
            return [
                {key: 'id', value: this.model['id']}
            ];
        },
        add(request) {
        },
        update(request) {
        },
        getTipOpts(name) {
            return {
                content: this.getError(name),
                closed: !this.hasError(name),
                position: "right"
            };
        },
        convertComboBoxData(object) {
            return toComboBoxData(object)
        },
    }
}